// pages/bulk-material-detail/bulk-material-detail.ts
import { getPublishDetail, participatePublish } from '../../../api/publish';
import { formatSpecification } from '../../../utils/util';
import { goToPage, PAGE_MEMBERSHIP_REGISTER } from '../../../config/pages';
import { getUserId, maskCompanyName, maskContactName, maskPhone, maskAddress, isPaidMember } from '../../../utils/userManager.js';

Page({
  data: {
    id: 0,
    detail: null as any,
    loading: true,
    isFavorite: false,
    isParticipated: false, // 是否已参与（已询价）
    submitting: false, // 提交中
    // 弹窗相关
    showInquiryModal: false,
    remark_corp: '',
    remark_name: '',
    remark_phone: '',
    remark_content: '',
  },

  onLoad(options: any) {
    if (options.id) {
      this.setData({ id: parseInt(options.id) });
      this.loadDetail();
    }
  },

  // 加载详情
  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(this.data.id);
      
      if (res.status === 200 && res.data) {
        // 格式化规格信息
        const formattedDetail = {
          ...res.data,
          spec: formatSpecification(res.data.spec || '')
        };
        
        // 检查是否为付费会员，如果不是则对联系方式进行脱敏
        const isPaid = isPaidMember();
        if (!isPaid && formattedDetail.user && formattedDetail.user.enterprise) {
          // 对企业信息进行脱敏处理
          formattedDetail.user.enterprise = {
            ...formattedDetail.user.enterprise,
            contact_name: maskContactName(formattedDetail.user.enterprise.contact_name || ''),
            contact_phone: maskPhone(formattedDetail.user.enterprise.contact_phone || ''),
            name: maskCompanyName(formattedDetail.user.enterprise.name || '')
          };
          
          // 对产品详情中的联系方式也进行脱敏
          if (formattedDetail.contact_name) {
            formattedDetail.contact_name = maskContactName(formattedDetail.contact_name);
          }
          if (formattedDetail.contact_phone) {
            formattedDetail.contact_phone = maskPhone(formattedDetail.contact_phone);
          }
          
          // 对地址进行脱敏处理
          if (formattedDetail.province || formattedDetail.city || formattedDetail.district) {
            const maskedAddress = maskAddress(formattedDetail.province, formattedDetail.city, formattedDetail.district);
            // 将脱敏后的地址保存到新的字段中，用于显示
            formattedDetail.maskedLocation = maskedAddress;
          }
        }
        
        // 格式化参与者时间
        if (formattedDetail.participants && formattedDetail.participants.length > 0) {
          const currentUserId = getUserId();
          const isOwner = currentUserId && formattedDetail.uid === currentUserId;
          
          formattedDetail.participants = formattedDetail.participants.map((participant: any) => {
            const isMine = currentUserId && (participant.uid === currentUserId || participant.user?.uid === currentUserId);
            
            // 显示逻辑：自己发布的单据显示完整信息，自己的接单显示明文，别人的接单显示密文
            let displayCompanyName = '';
            let displayContactName = '';
            let displayPhone = '';
            
            if (isOwner || isMine) {
              // 自己发布的单据或自己的接单，显示完整信息
              displayCompanyName = participant.user?.enterprise?.name || '';
              displayContactName = participant.user?.real_name || participant.user?.nickname || '';
              displayPhone = participant.user?.phone || '';
            } else {
              // 别人的接单，显示密文
              displayCompanyName = maskCompanyName(participant.user?.enterprise?.name || '');
              displayContactName = maskContactName(participant.user?.real_name || participant.user?.nickname || '');
              displayPhone = maskPhone(participant.user?.phone || '');
            }
            
            return {
              ...participant,
              add_time: this.formatTime(participant.add_time),
              isMine,
              avatar_name: this.getAvatarName(participant.user),
              displayCompanyName,
              displayContactName,
              displayPhone
            };
          });
        }
        
        this.setData({ detail: formattedDetail });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取头像名称
  getAvatarName(user: any) {
    if (!user) return '匿';
    
    // 优先使用real_name，其次nickname
    const name = user.real_name || user.nickname;
    if (!name || name === 'null' || name.length === 0) {
      return '匿';
    }
    
    return name.charAt(0);
  },

  // 格式化时间
  formatTime(timeStr: string) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    // 计算时间差
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) {
      return '刚刚';
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      // 超过7天显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}-${day} ${hour}:${minute}`;
      } else {
        return `${year}-${month}-${day} ${hour}:${minute}`;
      }
    }
  },

  // 切换收藏
  toggleFavorite() {
    this.setData({
      isFavorite: !this.data.isFavorite
    });
    wx.showToast({
      title: this.data.isFavorite ? '收藏成功' : '取消收藏',
      icon: 'success'
    });
  },

  // 跳转到企业详情页面
  goToCompanyProfile(e: any) {
    // 检查是否为付费会员
    if (!isPaidMember()) {
      wx.showModal({
        title: '需要付费会员',
        content: '查看企业详情需要购买付费会员，是否立即开通？',
        confirmText: '立即开通',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 跳转到会员注册页面
            goToPage(PAGE_MEMBERSHIP_REGISTER);
          }
        }
      });
      return;
    }
    
    const enterpriseId = e.currentTarget.dataset.enterpriseId;
    if (enterpriseId) {
      goToPage('/pages/enterprise/company-profile/company-profile', { enterpriseId });
    } else {
      wx.showToast({
        title: '企业信息不存在',
        icon: 'none'
      });
    }
  },

  // 举报
  reportMaterial() {
    wx.showActionSheet({
      itemList: ['虚假信息', '价格欺诈', '侵犯版权', '违法内容', '其他'],
      success: () => {
        wx.showModal({
          title: '确认举报',
          content: `确定要举报该散料吗？`,
          success: (modalRes) => {
            if (modalRes.confirm) {
              wx.showToast({
                title: '举报已提交',
                icon: 'success'
              });
            }
          }
        });
      }
    });
  },

  // 联系供应商
  contactSupplier() {
    // 检查是否为付费会员
    if (!isPaidMember()) {
      wx.showModal({
        title: '需要付费会员',
        content: '联系供应商需要购买付费会员，是否立即开通？',
        confirmText: '立即开通',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 跳转到会员注册页面
            goToPage(PAGE_MEMBERSHIP_REGISTER);
          }
        }
      });
      return;
    }
    
    if (this.data.detail) {
      wx.showModal({
        title: '联系供应商',
        content: `联系人：${this.data.detail.contact_name}\n电话：${this.data.detail.contact_phone}`,
        showCancel: true,
        confirmText: '拨打电话',
        success: (res) => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: this.data.detail.contact_phone
            });
          }
        }
      });
    }
  },

  // 立即询价 - 显示弹窗
  inquiryMaterial() {
    if (this.data.submitting) return;

    // 检查是否已询价
    if (this.data.isParticipated) {
      wx.showToast({
        title: '您已提交过询价',
        icon: 'none'
      });
      return;
    }

    // 检查是否是自己发布的
    if (this.data.detail && this.data.detail.is_owner) {
      wx.showToast({
        title: '不能参与自己发布的单据',
        icon: 'none'
      });
      return;
    }

    // 显示弹窗
    this.setData({ 
      showInquiryModal: true,
      remark_corp: '',
      remark_name: '',
      remark_phone: '',
      remark_content: ''
    });
  },

  // 关闭弹窗
  closeInquiryModal() {
    this.setData({ showInquiryModal: false });
  },

  // 输入框变化事件
  onInputChange(e: any) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [field]: value
    });
  },

  // 确认提交询价
  async confirmInquiry() {
    // 验证必填项 - 只有留言内容必填
    if (!this.data.remark_content.trim()) {
      wx.showToast({
        title: '请填写留言内容',
        icon: 'none'
      });
      return;
    }

    // 如果填写了手机号，验证手机号格式
    if (this.data.remark_phone.trim()) {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.data.remark_phone.trim())) {
        wx.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        });
        return;
      }
    }

    this.setData({ submitting: true });
    
    try {
      const result = await participatePublish(this.data.id, {
        remark_corp: this.data.remark_corp.trim(),
        remark_name: this.data.remark_name.trim(),
        remark_phone: this.data.remark_phone.trim(),
        remark_content: this.data.remark_content.trim()
      });
      
      if (result.status === 200 || result.code === 200) {
        this.setData({ 
          isParticipated: true,
          showInquiryModal: false
        });
        wx.showToast({
          title: '询价请求已发送',
          icon: 'success'
        });
        // 重新加载详情以获取最新参与状态
        this.loadDetail();
      } else {
        wx.showToast({
          title: result.msg || '询价失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('询价失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '询价失败，请重试'),
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 查看技术参数
  viewTechParams() {
    const { detail } = this.data;
    if (!detail) {
      wx.showToast({ title: '暂无技术参数', icon: 'none' });
      return;
    }

    const files = ([] as any[])
      .concat(detail.tech_params_files || [])
      .concat(detail.tech_params_atts || []);
    console.log(files);
    if (!files || files.length === 0) {
      wx.showToast({ title: '暂无技术参数', icon: 'none' });
      return;
    }

    const comp = this.selectComponent('#mediaViewer');
    if (comp && typeof (comp as any).open === 'function') {
      (comp as any).open(files);
    } else {
      wx.showToast({ title: '组件不可用', icon: 'none' });
    }
  },

  // 分享
  onShareAppMessage() {
    return {
      title: this.data.detail ? `${this.data.detail.product_name} - 散料` : '散料详情',
      path: `/pages/bulk-material-detail/bulk-material-detail?id=${this.data.id}`
    };
  }
});
